// models/user.js
const mongoose = require('../common/db');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        unique: true,
        trim: true,
        minlength: 3,
        maxlength: 20
    },
    password: {
        type: String,
        required: true,
        minlength: 6
    },
    email: {
        type: String,
        required: true,
        unique: true,
        match: [/.+\@.+\..+/, '请输入有效的邮箱地址']
    },
    phone: {
        type: String,
        required: true,
        unique: true,
        match: [/^[1][3-9][0-9]{9}$/, '请输入有效的手机号']
    },
    isAdmin: { type: Boolean, default: false },
    power: { type: Number, default: 0 },
    isActive: { type: Boolean, default: true },
    isOnline: { type: Boolean, default: false }
}, { timestamps: true });


userSchema.statics.query = async function (condition) {
    return await this.find(condition).exec();
}
// 添加静态方法
userSchema.statics.findByUsername = async function (username) {
    return await this.findOne({ username }).exec();
};

userSchema.statics.findByEmail = async function (email) {
    return await this.findOne({ email }).exec();
};

userSchema.statics.findByPhone = async function (phone) {
    return await this.findOne({ phone }).exec();
};

userSchema.methods.comparePassword = async function (password) {
    return await bcrypt.compare(password, this.password);
};

userSchema.pre('save', async function (next) {
    if (!this.isModified('password')) {
        return next();
    }
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
});

userSchema.statics.findByUserEmailPhone = async function (username, email, phone) {
    return await this.findOne({ username, email, phone }).exec();
};

userSchema.statics.findById = async function (id) {
    return await this.findOne({ _id: id }).exec();
};

userSchema.statics.findAll = async function () {
    return await this.find().select(
        'username email phone isActive isOnline createdAt updatedAt').exec();
};

// 添加实例方法
userSchema.methods.generateToken = function () {
    const token = jwt.sign({ _id: this._id }, process.env.JWT_SECRET, { expiresIn: '7d' });
    return 'Bearer ' + token;
};

// 权限验证
userSchema.statics.adminAuth = async function (id) {
    return await this.findOne({ _id: id, isAdmin: true, isActive: true }).exec();
};


// 导出模型

module.exports = mongoose.model('User', userSchema);
